package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.datamanage.PeopleNextData;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;
import com.wheel.StrericWheelAdapter;
import com.wheel.WheelView;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AnticipateOvershootInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class OvertimeApplyActivity extends BaseActivity implements OnClickListener
{
	private OvertimeApplyActivity context;
	private View main_view;
	private LayoutInflater inflater;
	private TextView nextPeople;
	private ArrayList<PeopleNextData> peoples_next;
	private RelativeLayout nextPeopleBg;

	// 滚动时间
	private WheelView yearWheel, monthWheel, dayWheel, hourWheel, minuteWheel;
	public static String[] yearContent = null;
	public static String[] monthContent = null;
	public static String[] dayContent = null;
	public static String[] hourContent = null;
	public static String[] minuteContent = null;

	private TextView startTime_l;
	private TextView endTime_l;

	private EditText alltime;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "OvertimeApplyActivity";
		context = this;
		inflater = LayoutInflater.from(this);
		main_view = inflater.inflate(R.layout.overtime_apply_view, null);
		setContentView(main_view);

		initview();
	}

	private void initview()
	{
		// 申请人
		EditText applyEdit = (EditText) findViewById(R.id.editText);
		applyEdit.setText(UserInfo.getUserInfor().getName());

		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 提交键
		ImageView uploadBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(context);
		uploadBtn.setOnClickListener(context);
		// 获取下一步处理人
		nextPeopleBg = (RelativeLayout) main_view.findViewById(R.id.next_people_bg);
		nextPeople = (TextView) main_view.findViewById(R.id.next_people);
		peoples_next = new ArrayList<PeopleNextData>();
		// 获取下一步处理人
		getNextPeople next = new getNextPeople();
		next.execute();

		initContent();

		startTime_l = (TextView) main_view.findViewById(R.id.editText22);
		startTime_l.setOnClickListener(this);
		endTime_l = (TextView) main_view.findViewById(R.id.editText23);
		endTime_l.setOnClickListener(this);

		alltime = (EditText) main_view.findViewById(R.id.editText3);
	}

	public void initContent()
	{
		yearContent = new String[10];
		for (int i = 0; i < 10; i++)
			yearContent[i] = String.valueOf(i + 2013);

		monthContent = new String[12];
		for (int i = 0; i < 12; i++)
		{
			monthContent[i] = String.valueOf(i + 1);
			if (monthContent[i].length() < 2)
			{
				monthContent[i] = "0" + monthContent[i];
			}
		}

		dayContent = new String[31];
		for (int i = 0; i < 31; i++)
		{
			dayContent[i] = String.valueOf(i + 1);
			if (dayContent[i].length() < 2)
			{
				dayContent[i] = "0" + dayContent[i];
			}
		}
		hourContent = new String[24];
		for (int i = 0; i < 24; i++)
		{
			hourContent[i] = String.valueOf(i);
			if (hourContent[i].length() < 2)
			{
				hourContent[i] = "0" + hourContent[i];
			}
		}

		minuteContent = new String[2];
		for (int i = 0; i < 2; i++)
		{
			// minuteContent[i]=String.valueOf(i);
			// if(minuteContent[i].length()<2)
			// {
			// minuteContent[i] = "0"+minuteContent[i];
			// }
			if (i == 0)
			{
				minuteContent[i] = "00";
			} else
			{
				minuteContent[i] = "30";
			}

		}
	}

	private void upload()
	{
		if (isCanUpload())
		{
			UpdateLoadInfo upload = new UpdateLoadInfo();
			upload.execute();
		}
	}

	/*
	 * 传送数据到服务器
	 */
	private class UpdateLoadInfo extends AsyncTask<String, Integer, String>
	{
		private MyLoadingDialog mydiog;

		// private ProgressDialog mProgress;
		public UpdateLoadInfo() {

		}

		@Override
		protected void onPreExecute()
		{
			mydiog = new MyLoadingDialog(context, null, "提交中...", false);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try
			{

				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				EditText text = (EditText) main_view.findViewById(R.id.editText1);
				vs.add(new BasicNameValuePair("reason", text.getText().toString()));
				vs.add(new BasicNameValuePair("startDate", startTime_l.getText().toString()));
				vs.add(new BasicNameValuePair("endDate", endTime_l.getText().toString()));
				vs.add(new BasicNameValuePair("overtimes",
						"" + subTime(startTime_l.getText().toString(), endTime_l.getText().toString())));
				vs.add(new BasicNameValuePair("workOvertimeType", "时"));

				response = LinkHelp.post(URLS.getOverTimeStart(), vs, false);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			mydiog.dimiss();

			if (result == null)
			{
				ToastHelp.doToast(context, "网络异常！");
				return;
			}

			JSONObject jsonObject;
			try
			{
				jsonObject = new JSONObject(result);
				if (jsonObject.isNull("code"))
				{
					String status = jsonObject.getString("status");
					UserInfo info = UserInfo.getUserInfor();
					if (status.equals("success"))
					{
						Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show();

						finish();
					} else
					{
						String msg = jsonObject.getString("msg");
						// Toast.makeText(context, msg,
						// Toast.LENGTH_SHORT).show();
						ToastHelp.doToast(context, msg);
					}

				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}

	private boolean isCanUpload()
	{
		EditText text = (EditText) main_view.findViewById(R.id.editText1);
		if (text.getText().toString() == null || text.getText().toString().equals(""))
		{
			ToastHelp.doToast(context, "请填写加班原因");
			return false;
		}

		if (startTime_l.getText().toString() == null || startTime_l.getText().toString().equals(""))
		{
			ToastHelp.doToast(context, "请填写起始加班时间");
			return false;
		}

		if (endTime_l.getText().toString() == null || endTime_l.getText().toString().equals(""))
		{
			ToastHelp.doToast(context, "请填写结束加班时间");
			return false;
		}

		if (subTime(startTime_l.getText().toString(), endTime_l.getText().toString()) < 0.5
				|| subTime(startTime_l.getText().toString(), endTime_l.getText().toString()) > 99)
		{
			ToastHelp.doToast(context, "加班时间不能大于99，且为0.5的倍数");
			return false;
		}
		return true;
	}

	// 获取下一步处理人
	private class getNextPeople extends AsyncTask<String, Integer, String>
	{

		// private ProgressDialog mProgress;
		public getNextPeople() {
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try
			{
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				vs.add(new BasicNameValuePair("taskId", ""));
				response = LinkHelp.post(URLS.getNextWorkUser("overtime"), vs, false);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{

			if (result == null)
			{
				ToastHelp.doToast(context, "网络异常！");
				return;
			}

			JSONObject jsonObject;
			try
			{
				jsonObject = new JSONObject(result);
				if (jsonObject.isNull("code"))
				{
					String status = jsonObject.getString("status");
					if (status.equals("success"))
					{
						{
							if (result.contains("workUserInfo"))
							{
								JSONArray peoples = jsonObject.getJSONArray("workUserInfo");
								for (int i = 0; i < peoples.length(); i++)
								{
									PeopleNextData data = new PeopleNextData();
									JSONObject myJS = peoples.getJSONObject(i);
									data.setUserId(myJS.getString("userId"));
									data.setUserName(myJS.getString("userName"));
									data.setDepartmentId(myJS.getString("departmentId"));
									data.setDepartmentName(myJS.getString("departmentName"));
									data.setCompanyId(myJS.getString("companyId"));
									data.setCompanyName(myJS.getString("companyName"));
									data.setIsHead(myJS.getString("isHead"));
									data.setCode(myJS.getString("code"));
									peoples_next.add(data);
								}
								if (peoples_next.size() >= 1)
								{
									nextPeople.setText(peoples_next.get(0).getUserName() + "("
											+ peoples_next.get(0).getDepartmentName() + ")");
								} else
								{
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else if (result.contains("noNeedWorkUserId"))
							{
								if (jsonObject.getString("noNeedWorkUserId").equals("true"))
								{
									nextPeople.setText("下一步不需要处理人");
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else if (result.contains("msg"))
							{
								nextPeople.setText(jsonObject.getString("msg"));

								if (jsonObject.getString("msg").contains("不需要"))
								{
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else
							{
								System.out.println("Shit!服务器给的什么破数据");
							}

						}

					} else
					{
						String msg = jsonObject.getString("msg");
						// Toast.makeText(context, msg,
						// Toast.LENGTH_SHORT).show();
						ToastHelp.doToastInTop(context, msg);
						nextPeople.setText("空");
						nextPeopleBg.setVisibility(View.GONE);
					}

				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}

	@Override
	public void onClick(View arg0)
	{
		// TODO Auto-generated method stub
		int id = arg0.getId();
		// //隐藏软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(main_view.getWindowToken(), 0);

		getCurrentFocus().clearFocus();
		EditText edit = (EditText) main_view.findViewById(R.id.edit_focuse_unable);
		edit.setFocusable(true);
		edit.requestFocus();

		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;

		case R.id.title_bar_btn_right:
			upload();
			break;
		case R.id.editText22:
		{
			final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
			 alertDialog.setCanceledOnTouchOutside(true);
			Window window = alertDialog.getWindow();
	        window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.pop_float_win_anim_style);
           
			alertDialog.show();
			window.setContentView(R.layout.custom_alert_dialog); 
			
			View view = window.findViewById(R.id.time_picker);

			Calendar calendar = Calendar.getInstance();
			int curYear = calendar.get(Calendar.YEAR);
			int curMonth = calendar.get(Calendar.MONTH) + 1;
			int curDay = calendar.get(Calendar.DAY_OF_MONTH);
			int curHour = calendar.get(Calendar.HOUR_OF_DAY);
			int curMinute = calendar.get(Calendar.MINUTE);

			yearWheel = (WheelView) view.findViewById(R.id.yearwheel);
			monthWheel = (WheelView) view.findViewById(R.id.monthwheel);
			dayWheel = (WheelView) view.findViewById(R.id.daywheel);
			hourWheel = (WheelView) view.findViewById(R.id.hourwheel);
			minuteWheel = (WheelView) view.findViewById(R.id.minutewheel);

			yearWheel.setAdapter(new StrericWheelAdapter(yearContent));
			yearWheel.setCurrentItem(curYear - 2013);
			yearWheel.setCyclic(true);
			yearWheel.setInterpolator(new AnticipateOvershootInterpolator());

			monthWheel.setAdapter(new StrericWheelAdapter(monthContent));

			monthWheel.setCurrentItem(curMonth - 1);

			monthWheel.setCyclic(true);
			monthWheel.setInterpolator(new AnticipateOvershootInterpolator());

			dayWheel.setAdapter(new StrericWheelAdapter(dayContent));
			dayWheel.setCurrentItem(curDay - 1);
			dayWheel.setCyclic(true);
			dayWheel.setInterpolator(new AnticipateOvershootInterpolator());

			hourWheel.setAdapter(new StrericWheelAdapter(hourContent));
			hourWheel.setCurrentItem(curHour);
			hourWheel.setCyclic(true);
			hourWheel.setInterpolator(new AnticipateOvershootInterpolator());

			minuteWheel.setAdapter(new StrericWheelAdapter(minuteContent));
			minuteWheel.setCurrentItem(curMinute);
			minuteWheel.setCyclic(false);
			minuteWheel.setInterpolator(new AnticipateOvershootInterpolator());

//			builder.setTitle("起始时间");
			 window.findViewById(R.id.cancel_btn).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v)
				{
					StringBuffer sb = new StringBuffer();
					sb.append(yearWheel.getCurrentItemValue()).append("-").append(monthWheel.getCurrentItemValue())
							.append("-").append(dayWheel.getCurrentItemValue());

					sb.append(" ");
					sb.append(hourWheel.getCurrentItemValue()).append(":").append(minuteWheel.getCurrentItemValue());
					startTime_l.setText(sb);
					if (!endTime_l.getText().toString().equals("") && endTime_l.getText().toString() != null)
					{
						float allTime = subTime(startTime_l.getText().toString(), endTime_l.getText().toString());
						if (allTime > 0)
						{
							alltime.setText("" + allTime);
						}else
						{
							startTime_l.setText("");
							ToastHelp.doToast(context, "开始时间不能大于结束时间，请重新输入！");
						}
					}

					alertDialog.cancel();
				
				}
			});
			

		}
			break;
		case R.id.editText23:
		{
			final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
			Window window = alertDialog.getWindow();
	        window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.pop_float_win_anim_style);
            alertDialog.setCanceledOnTouchOutside(true);
			alertDialog.show();
			window.setContentView(R.layout.custom_alert_dialog); 
			View view = window.findViewById(R.id.time_picker);
			
			Calendar calendar = Calendar.getInstance();
			int curYear = calendar.get(Calendar.YEAR);
			int curMonth = calendar.get(Calendar.MONTH) + 1;
			int curDay = calendar.get(Calendar.DAY_OF_MONTH);
			int curHour = calendar.get(Calendar.HOUR_OF_DAY);
			int curMinute = calendar.get(Calendar.MINUTE);

			yearWheel = (WheelView) view.findViewById(R.id.yearwheel);
			monthWheel = (WheelView) view.findViewById(R.id.monthwheel);
			dayWheel = (WheelView) view.findViewById(R.id.daywheel);
			hourWheel = (WheelView) view.findViewById(R.id.hourwheel);
			minuteWheel = (WheelView) view.findViewById(R.id.minutewheel);

		

			yearWheel.setAdapter(new StrericWheelAdapter(yearContent));
			yearWheel.setCurrentItem(curYear - 2013);
			yearWheel.setCyclic(true);
			yearWheel.setInterpolator(new AnticipateOvershootInterpolator());

			monthWheel.setAdapter(new StrericWheelAdapter(monthContent));

			monthWheel.setCurrentItem(curMonth - 1);

			monthWheel.setCyclic(true);
			monthWheel.setInterpolator(new AnticipateOvershootInterpolator());

			dayWheel.setAdapter(new StrericWheelAdapter(dayContent));
			dayWheel.setCurrentItem(curDay - 1);
			dayWheel.setCyclic(true);
			dayWheel.setInterpolator(new AnticipateOvershootInterpolator());

			hourWheel.setAdapter(new StrericWheelAdapter(hourContent));
			hourWheel.setCurrentItem(curHour);
			hourWheel.setCyclic(true);
			hourWheel.setInterpolator(new AnticipateOvershootInterpolator());

			minuteWheel.setAdapter(new StrericWheelAdapter(minuteContent));
			minuteWheel.setCurrentItem(curMinute);
			minuteWheel.setCyclic(false);
			minuteWheel.setInterpolator(new AnticipateOvershootInterpolator());

//			builder.setTitle("结束时间");
			 window.findViewById(R.id.cancel_btn).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v)
				{
					StringBuffer sb = new StringBuffer();
					sb.append(yearWheel.getCurrentItemValue()).append("-").append(monthWheel.getCurrentItemValue())
							.append("-").append(dayWheel.getCurrentItemValue());

					sb.append(" ");
					sb.append(hourWheel.getCurrentItemValue()).append(":").append(minuteWheel.getCurrentItemValue());
					endTime_l.setText(sb);

					if (!startTime_l.getText().toString().equals("") && startTime_l.getText().toString() != null)
					{
						float allTime = subTime(startTime_l.getText().toString(), endTime_l.getText().toString());
						if (allTime > 0)
						{
							alltime.setText("" + allTime);
						}else
						{
							endTime_l.setText("");
							ToastHelp.doToast(context, "结束时间不能小于开始时间，请重新输入！");
						}
					}

					alertDialog.cancel();
					
				}
			});
			

		}
			break;

		default:
			break;
		}

	}

	private float subTime(String start, String end)
	{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try
		{
			Date d1 = df.parse(start);
			Date d2 = df.parse(end);
			long diff = d2.getTime() - d1.getTime();
			long days = diff / (1000 * 60 * 60 * 24);
			long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
			long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
			if (minutes >= 30)
			{
				return days * 24 + hours + 0.5f;
			} else
			{
				return days * 24 + hours;
			}
		} catch (ParseException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

}
